import { createRouter, createWebHashHistory } from "vue-router";
import { StorageUtil } from '@/utils/storage';
import HomeView from "../views/HomeView.vue";
import ConfigView from '../views/ConfigView.vue'
import AccountView from '../views/AccountView.vue'
import HistoryView from '../views/HistoryView.vue'
import LoginView from '../views/LoginView.vue'

const routes = [
  {
    path: "/login",
    name: "login",
    component: LoginView
  },
  {
    path: "/",
    name: "home",
    component: HomeView,
    redirect: '/config',
    children: [
      {
        path: 'config',
        name: 'config',
        component: ConfigView
      },
      {
        path: 'account',
        name: 'account',
        component: AccountView
      },
      {
        path: 'history',
        name: 'history',
        component: HistoryView
      }
    ]
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 导航守卫
router.beforeEach((to, from, next) => {
  let cardKey = ""

  const hash = to.href; // 获取哈希部分

  // 提取哈希部分的查询参数
  const queryString = hash.includes('?') ? hash.split('?')[1] : '';

  if (queryString) {
    const urlParams = new URLSearchParams(queryString); // 解析查询参数

    cardKey = urlParams.get('cardKey') || ''; // 返回 cardKey 值
  }

  // 如果没有token且不是登录页，重定向到登录页
  if (!cardKey && to.name !== 'login') {
    next({ name: 'login' })
  } else if (cardKey && to.name === 'login') {
    next({ name: 'home' })
  } else {
    next()
  }

});

export default router;
